package api

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io"
	"time"
	"zsc-boot/app/customer/model"
	"zsc-boot/app/customer/model/request"
	"zsc-boot/core"
	"zsc-boot/core/orm"
	"zsc-boot/core/utils"
	"zsc-boot/core/web"
)

type CustomerImportApi struct {
}

// FyCreate 对接飞鱼
func (c *CustomerImportApi) FyCreate(ctx *gin.Context) {
	//signature := ctx.GetHeader("Signature")
	token := ctx.GetHeader("access-token")
	core.GetLogger().Warn(token)
	//timestamp := ctx.GetHeader("Timestamp")
	//验签
	body := bytes.NewBuffer(nil)
	_, _ = io.Copy(body, ctx.Request.Body)
	core.GetLogger().Warn(body.String())

	var req FyReq
	_ = json.Unmarshal(body.Bytes(), &req)

	var channelModel model.CustomerChannel
	if err := orm.GetDb().Where("uuid = ?", token).First(&channelModel).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	if !channelModel.Status {
		web.FailResponse(ctx, nil, "渠道停用")
		return
	}
	var createData model.CustomerImportLog
	createData.Name = req.Name
	createData.Mobile = req.Telphone
	createData.ChannelId = channelModel.ID
	createData.ChannelName = channelModel.Name
	createData.City = req.CityName
	createData.Age = uint8(req.Age)

	//判断是否重复
	var oldData model.CustomerImportLog
	if err := orm.GetDb().Where("mobile = ?", createData.Mobile).Find(&oldData).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	if oldData.ID != 0 {
		createData.IsRepeated = true
	}

	if err := orm.Create[model.CustomerImportLog](createData); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	web.SuccessResponse(ctx, nil)

	//hasher := sha256.New()
	//hasher.Write([]byte(req.Id + token + timestamp))
	//hashBytes := hasher.Sum(nil)
	//encoded := base64.StdEncoding.EncodeToString(hashBytes)
	//if encoded != signature {
	//	web.FailResponse(ctx, errors.New("验签失败"), "验签失败")
	//	return
	//}
	//验签
}

func (c *CustomerImportApi) ApiCreate(ctx *gin.Context) {
	var req request.CustomerImportReq
	_ = ctx.ShouldBind(&req)

	//验签
	var channelModel model.CustomerChannel
	if err := orm.GetDb().Where("uuid = ?", req.UUID).First(&channelModel).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	if !channelModel.Status {
		web.FailResponse(ctx, nil, "渠道停用")
		return
	}

	if utils.MD5V([]byte(channelModel.SecretKey+req.Time)) != req.SecretKeyMd5 {
		web.FailResponse(ctx, nil, "密钥异常")
		return
	}

	req.ChannelName = channelModel.Name
	req.ChannelId = channelModel.ID

	reqTime, err := time.ParseInLocation(time.DateTime, req.Time, time.Local)
	if err != nil {
		web.FailResponse(ctx, err, "时间格式错误")
		return
	}
	//
	//if time.Now().Sub(reqTime) > 5*time.Second {
	//	web.FailResponse(ctx, nil, "数据过期")
	//	return
	//}
	req.CreatedAt = orm.LocalTime(reqTime)

	//判断是否重复
	var oldData model.CustomerImportLog
	if err = orm.GetDb().Where("mobile = ?", req.Mobile).Find(&oldData).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	if oldData.ID != 0 {
		req.IsRepeated = true
	}

	if err = orm.Create[model.CustomerImportLog](req.CustomerImportLog); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	web.SuccessResponse(ctx, nil)
}

func (c *CustomerImportApi) Check(ctx *gin.Context) {
	mobile := ctx.Query("mobile")
	if mobile == "" {
		web.FailResponse(ctx, nil, "请传入手机号")
		return
	}

	var oldData model.CustomerImportLog
	if err := orm.GetDb().Where("mobile = ?", mobile).Find(&oldData).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	if oldData.ID != 0 {
		web.FailResponse(ctx, nil, "客户已存在")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

func (c *CustomerImportApi) Create(ctx *gin.Context) {
	var req model.CustomerImportLog
	_ = ctx.ShouldBind(&req)

	//判断是否重复
	var oldData model.CustomerImportLog
	if err := orm.GetDb().Where("mobile = ?", req.Mobile).Find(&oldData).Error; err != nil {
		web.FailResponse(ctx, nil, "服务异常")
		return
	}

	if oldData.ID != 0 {
		web.FailResponse(ctx, nil, "客户已存在")
		return
	}

	req.ChannelId = 1
	req.ChannelName = "系统渠道"
	if err := orm.Create[model.CustomerImportLog](req); err != nil {
		web.FailResponse(ctx, nil, "服务异常")
		return
	}
	web.SuccessResponse(ctx, nil)
}

func (c *CustomerImportApi) List(ctx *gin.Context) {
	var req request.CustomerImportListReq
	_ = ctx.BindQuery(&req)

	db := orm.GetDb().Model(&model.CustomerImportLog{})
	if req.IsAllocation != nil {
		db = db.Where("is_allocation = ?", req.IsAllocation)
	}
	if req.Name != "" {
		db = db.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.City != "" {
		db = db.Where("city LIKE ?", "%"+req.City+"%")
	}

	if req.ChannelId != 0 {
		db = db.Where("channel_id = ?", req.ChannelId)
	}

	if req.IsRepeated != nil {
		db = db.Where("is_repeated = ?", req.IsRepeated)
	}

	if req.UserId != 0 {
		db = db.Where("user_id = ?", req.UserId)
	}
	if req.StartDate != "" && req.EndDate != "" {
		db = db.Where("created_at >= ? and created_at<= ?", req.StartDate+" 00:00:00", req.EndDate+" 23:59:59")
	}

	var (
		count int64
		list  []model.CustomerImportLog
	)
	if err := db.Count(&count).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	if err := db.Order("created_at desc").Preload("UserInfo").Offset((req.Page - 1) * req.PageSize).
		Preload("ChannelInfo").Limit(req.PageSize).Find(&list).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	for k, _ := range list {
		if len(list[k].Remark) > 8 {
			list[k].Remark = list[k].Remark[0:8] + "..."
		}
	}

	web.SuccessListResponse(ctx, list, count, req.Page, req.PageSize)
}

func (c *CustomerImportApi) Detail(ctx *gin.Context) {
	var req core.GetById
	_ = ctx.Bind(&req)

	if data, err := orm.Detail[model.CustomerImportLog](int(req.ID), "ChannelInfo", "UserInfo"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
	} else {
		web.SuccessResponse(ctx, data)
	}
}

func (c *CustomerImportApi) Delete(ctx *gin.Context) {
	var req core.GetById
	_ = ctx.Bind(&req)

	if err := orm.Delete[model.CustomerImportLog](req.ID); err != nil {
		web.FailResponse(ctx, err, "服务异常")
	} else {
		web.SuccessResponse(ctx, "")
	}
}

type FyReq struct {
	AdvId         string `json:"adv_id"`
	AppName       string `json:"app_name"`
	ConvertStatus int    `json:"convert_status"`
	ModuleId      string `json:"module_id"`
	City          string `json:"city"`
	StoreName     string `json:"store_name"`
	Location      string `json:"location"`
	BusinessDict  struct {
	} `json:"business_dict"`
	ClueSource           int    `json:"clue_source"`
	Weixin               string `json:"weixin"`
	AdvName              string `json:"adv_name"`
	AdvertiserId         string `json:"advertiser_id"`
	AdName               string `json:"ad_name"`
	Qq                   string `json:"qq"`
	Name                 string `json:"name"`
	Cid                  int    `json:"cid"`
	Gender               string `json:"gender"`
	ModuleName           string `json:"module_name"`
	ExternalUrl          string `json:"external_url"`
	SiteName             string `json:"site_name"`
	StoreId              int    `json:"store_id"`
	Telphone             string `json:"telphone"`
	CreateTime           string `json:"create_time"`
	ClueConvertStatus    string `json:"clue_convert_status"`
	Id                   string `json:"id"`
	FormRemark           string `json:"form_remark"`
	Email                string `json:"email"`
	ProvinceName         string `json:"province_name"`
	AdId                 string `json:"ad_id"`
	Address              string `json:"address"`
	CityName             string `json:"city_name"`
	Age                  int    `json:"age"`
	ModifyTime           string `json:"modify_time"`
	ReqId                string `json:"req_id"`
	ClueDataSourceDetail string `json:"clue_data_source_detail"`
	FlowType             string `json:"flow_type"`
	MidInfo              struct {
		TitleId int `json:"titleId"`
		VideoId int `json:"videoId"`
		ImageId int `json:"imageId"`
	} `json:"mid_info"`
}
